package com.huangzhao.gulimall.product.web;

import com.huangzhao.gulimall.product.entity.CategoryEntity;
import com.huangzhao.gulimall.product.service.CategoryService;
import com.huangzhao.gulimall.product.vo.Catalog2Vo;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author huangzhao
 */
@Log4j2
@Controller
public class IndexController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(value = {"/", "index.html"})
    public String indexPage(Model model, HttpSession session) {
        log.info("threadName:{}", Thread.currentThread().getName());
        //1、查出所有的一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categories", categoryEntities);

        return "index";
    }

    //index/json/catalog.json
    @GetMapping(value = "/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson() {

        Map<String, List<Catalog2Vo>> catalogJson = categoryService.getCatalogJson();

        return catalogJson;

    }

    @ResponseBody
    @RequestMapping("hello")
    public String hello() {
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();
        //1）、锁的自动续期，如果业务超长，运行期间自动锁上新的30s。不用担心业务时间长，锁自动过期被删掉
        //2）、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认会在30s内自动过期，不会产生死锁问题
        // myLock.lock(10,TimeUnit.SECONDS);   //10秒钟自动解锁,自动解锁时间一定要大于业务执行时间
        //问题：在锁时间到了以后，不会自动续期
        //1、如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是 我们制定的时间
        //2、如果我们指定锁的超时时间，就使用 lockWatchdogTimeout = 30 * 1000 【看门狗默认时间】
        //只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗的默认时间】,每隔10秒都会自动的再次续期，续成30秒
        // internalLockLeaseTime 【看门狗时间】 / 3， 10s
        try {
            log.info("加锁成功，执行业务，threadName:{}", Thread.currentThread().getId());
            TimeUnit.SECONDS.sleep(15);
        } catch (Exception e) {
        } finally {
            log.info("释放锁，threadName:{}", Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    /**
     * 保证一定能读到最新数据，修改期间，写锁是一个排它锁（互斥锁、独享锁），读锁是一个共享锁
     * 写锁没释放读锁必须等待
     * 读 + 读 ：相当于无锁，并发读，只会在Redis中记录好，所有当前的读锁。他们都会同时加锁成功
     * 写 + 读 ：必须等待写锁释放
     * 写 + 写 ：阻塞方式
     * 读 + 写 ：有读锁。写也需要等待
     * 只要有读或者写的存都必须等待
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/write")
    public String write() {
        String uuid = "";
        RReadWriteLock readWriteLick = redissonClient.getReadWriteLock("readWriteLick");
        RLock rLock = readWriteLick.writeLock();
        rLock.lock();
        try {
            uuid = UUID.randomUUID().toString();
            stringRedisTemplate.opsForValue().set("writeValue", uuid);
            TimeUnit.SECONDS.sleep(15);
        } catch (Exception e) {

        } finally {
            rLock.unlock();
        }
        return uuid;
    }

    @ResponseBody
    @RequestMapping("/read")
    public String read() {
        String writeValue = "";
        RReadWriteLock readWriteLick = redissonClient.getReadWriteLock("readWriteLick");
        RLock rLock = readWriteLick.readLock();
        try {
            rLock.lock();
            writeValue = stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
        } finally {
            rLock.unlock();
        }
        return writeValue;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量也可以做分布式限流
     */
    @GetMapping(value = "/park")
    @ResponseBody
    public String park() throws InterruptedException {

        RSemaphore park = redissonClient.getSemaphore("park");
        park.acquire();     //获取一个信号、获取一个值,占一个车位
        boolean flag = park.tryAcquire();

        if (flag) {
            //执行业务
        } else {
            return "error";
        }

        return "ok=>" + flag;
    }

    @GetMapping(value = "/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();     //释放一个车位
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/schoolClose")
    public String schoolClose() {
        RCountDownLatch schoolCloseLock = redissonClient.getCountDownLatch("schoolClose");
        schoolCloseLock.trySetCount(5);
        try {
            schoolCloseLock.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "学校关门，放假啦...";
    }

    @ResponseBody
    @RequestMapping("/classOff/{id}")
    public String classOff(@PathVariable("id") Long id) {
        RCountDownLatch schoolCloseLock = redissonClient.getCountDownLatch("schoolClose");
        schoolCloseLock.countDown();
        return id + "班离开了...";
    }

}
